package com.kawa.kw_pay;

import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

import com.unionpay.UPPayAssistEx;

import org.json.JSONException;
import org.json.JSONObject;

public class UPPayUtils {
    private static UPPayUtils singletonLazy;

    private UPPayUtils() {}

    private static synchronized UPPayUtils getInstance() {
        try {
            if (null == singletonLazy) {
                singletonLazy = new UPPayUtils();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return singletonLazy;
    }

    private Activity mActivity;
    private Callback callback;



    public static void registerActivity(Activity activity){
        getInstance().mActivity = activity;
    }

    public static void handlerResult(Intent data){
        if (data == null) {
            return;
        }
        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String resultData = "";
        String str = data.getExtras().getString("pay_result");
        if (str == null){
            return;
        }
        if (data.hasExtra("result_data")) {
            resultData = data.getExtras().getString("result_data");
        }
        if (getInstance().callback != null){
            getInstance().callback.onResult(str,resultData);
        }
        if (str.equalsIgnoreCase("success")) {

            // 如果想对结果数据验签，可使用下面这段代码，但建议不验签，直接去商户后台查询交易结果
            // result_data结构见c）result_data参数说明
            if (data.hasExtra("result_data")) {
                String result = data.getExtras().getString("result_data");
                try {
                    JSONObject resultJson = new JSONObject(result);
                    String sign = resultJson.getString("sign");
                    String dataOrg = resultJson.getString("data");
                } catch (JSONException e) {
                    return;
                }
            }
            // 结果result_data为成功时，去商户后台查询一下再展示成功
            msg = "支付成功！";
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "用户取消了支付";
        }
    }

    /**
     * 发起银联支付
     * @param tn 订单流水号
     * @param mode 环境 00 正式 01 测试
     */
    public static void startUPPay(String tn,String mode,Callback callback){
        if (getInstance().mActivity == null){
//            Toast.makeText(ActivityUtils.getTopActivity(),"请先注册支付工具",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!UPPayAssistEx.checkWalletInstalled(getInstance().mActivity)){
            Toast.makeText(getInstance().mActivity, "请先安装云闪付后",Toast.LENGTH_SHORT).show();
            return;
        }
        UPPayAssistEx.startPay(getInstance().mActivity,null,null,tn,mode);
        getInstance().callback = callback;
    }

    public static interface Callback{
        void onResult(String result, String data);
    }
}
